import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/ui/service_order/service_order_detail_page.dart';

import '../../net/response/service_order_list_data.dart';
import '../../viewmodel/service_order/service_order_list_view_model.dart';
import '../../viewmodel/service_order/simple_service_order_list_view_model.dart';

class SimpleServiceOrderListPage extends BaseStatefulMvvmWidget {
  @override
  State<StatefulWidget> createState() => _SimpleServiceOrderListState();
}

class _SimpleServiceOrderListState extends BaseMvvmListState<
    SimpleServiceOrderListViewModel, SimpleServiceOrderListPage> {
  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text('服务单列表'),
      ),
      body: Column(
        children: [
          SizedBox(height: 12,),
          Padding(padding: EdgeInsets.symmetric(horizontal: 12),child: filterWidget(hint: '预约日期',value: vm?.startDateStr,onClearClick: (){
            setState(() {
              vm?.startDateStr = "";
            });
          }).onTap((){
            viewModel.selectStartDate(click: (date){
              viewModel.requestRefresh();
            });
          }),),

          SizedBox(height: 10,),

          Row(
            children: [
              SizedBox(width: 12,),
              ...[
                filterWidget(hint: '在住类型',value: vm?.type?.name,onClearClick: (){
                  setState(() {
                    vm?.type = null;
                  });
                }).onTap((){
                  viewModel.chooseType();
                }).setWeight(1),

                filterWidget(hint: '服务项目',value: vm?.serviceItem?.name,onClearClick: (){
                  setState(() {
                    vm?.serviceItem = null;
                    vm?.serviceContent = null;
                  });
                }).onTap((){
                  viewModel.chooseServiceItem();
                }).setWeight(1),

                filterWidget(hint: '服务内容',value: vm?.serviceContent?.name,onClearClick: (){
                  setState(() {
                    vm?.serviceContent = null;
                  });
                }).onTap((){
                  viewModel.chooseServiceContent();

                }).setWeight(1),
              ].
              insertWidget(SizedBox(width: 10,)),
              SizedBox(width: 12,),
            ],
          ),

          SizedBox(height: 10,),
          loadingContentWidget.setWeight(1)
        ],
      ),
    );
  }

  Widget filterWidget({required String hint, String? value,Function()? onClearClick}){
    return Row(
      children: [
        Text(value.isNullOrEmpty()?hint:value!,style: TextStyle(
          color: value.isNullOrEmpty()?Colors.grey:Colors.black
        ),maxLines: 1,).setWeight(1),
        if(!value.isNullOrEmpty())
          Icon(Icons.clear,color: Colors.white,size: 15,).addToContainer(
              decoration: BoxDecoration(
                color: Colors.black,
                shape: BoxShape.circle,
              )
          ).onTap((){
            onClearClick?.call();
            viewModel.requestRefresh();
          }),

        Icon(Icons.arrow_drop_down)
      ],
    ).addToContainer(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: 20.borderRadius,
      ),
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
    );
  }

  @override
  Widget createItemWidget(int index) {
    var item = viewModel.listItems[index];
    return Stack(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                CommonText('工单编号：${item.orderServeCode}',
                        textSize: 14, textColor: Color(0xff848689))
                    .setWeight(1),
                CommonText('${item.statusName}',
                    textSize: 15, textColor: statusColor(item.statusId))
              ],
            ),
            Container(
              height: 5,
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Icon(
                  Icons.house_rounded,
                  color: Colors.white,
                )
                    .addToContainer(
                        decoration: BoxDecoration(
                            color: Color(0xff3EB9AC),
                            borderRadius: 8.borderRadius),
                        width: 40,
                        height: 40)
                    .addToContainer(margin: EdgeInsets.only(top: 4, right: 12)),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      height: 8,
                    ),
                    Row(children: [
                      CommonText('${item.orderServeItemName}',
                              textSize: 18, fontWeight: FontWeight.w600)
                          .setWeight(1),
                      if (item.type != null)
                        CommonText(item.typeName,
                                textSize: 14, textColor: Colors.white)
                            .addToContainer(
                                decoration: BoxDecoration(
                                  color: item.type == 1
                                      ? Colors.orange
                                      : Color(0xff3EB9AC),
                                ),
                                padding: EdgeInsets.symmetric(
                                    horizontal: 8, vertical: 3))
                    ]),
                    Container(
                      height: 8,
                    ),
                    CommonText('预约时间：${item.markDuration ?? ""}',
                        textSize: 14, textColor: Color(0xff848689)),
                    Container(
                      height: 5,
                    ),
                    CommonText('服务对象：${item.orderServeHuman ?? ""}',
                        textSize: 14, textColor: Color(0xff848689)),
                    Container(
                      height: 5,
                    ),
                    CommonText('服务地址：${item.orderServeAddress ?? ""}',
                        textSize: 14, textColor: Color(0xff848689)),
                    Container(
                      height: 5,
                    ),
                    CommonText('联系电话：${item.humanMobile ?? ""}',
                        textSize: 14, textColor: Color(0xff848689)),
                    Container(
                      height: 5,
                    ),
                    CommonText(
                        '楼栋楼层：${item.buildingName ?? ""}-${item.floorName ?? ""}',
                        textSize: 14,
                        textColor: Color(0xff848689)),

                    if(!item.site.isNullOrEmpty())
                      ...[
                        Container(
                          height: 5,
                        ),

                        CommonText(
                            '站点：${item.site}',
                            textSize: 14,
                            textColor: Color(0xff848689)),
                      ],
                    Container(
                      height: 8,
                    ),
                    btnList(item, item.id!)
                        .addToContainer(width: double.infinity)
                  ],
                ).setWeight(1)
              ],
            )
          ],
        ),
      ],
    ).onTap(() {
      Go().push(ServiceOrderDetailPage(
        showDetail: true,
        orderId: item.id!,
        handleStatus: handleStatus(item.statusId!),
      ));
    }).addToContainer(
        decoration:
            BoxDecoration(color: Colors.white, borderRadius: 8.borderRadius),
        margin: EdgeInsets.symmetric(
          horizontal: 16,
        ),
        padding: EdgeInsets.all(10));
  }

  Color statusColor(String? statusId) {
    switch (statusId) {
      case '10233':
        return Color(0xffFD625F);

      case '10235':
      case '10236':
        return Color(0xff3EB9AC);
      default:
        return Colors.blue;
    }
  }

  List<Map<String, String>> btnStrs(ServiceOrderListData item) {
    var statusId = item.statusId;
    var isFood = item.orderServeTypeName?.contains("用餐")==true;
    switch (statusId) {
      case '10231':
      case '10234':
        return [
          if(viewModel.canSend)
          {"name": "派单", "value": "待派单"},
          if(viewModel.canReceive)
          {"name": "接单", "value": "待接单"},
          if (!isFood && viewModel.canStartOrder)
            {"name": "开始服务", "value": "待开始"}
          else
            if(viewModel.canFinishOrder)
            {"name": "完成服务", "value": "待完成"},
        ];
      case '10233':
        return [
          if(viewModel.canReceive)
          {"name": "接单", "value": "待接单"},
          if (!isFood&&viewModel.canStartOrder)
            {"name": "开始服务", "value": "待开始"}
          else
            if(viewModel.canFinishOrder)
            {"name": "完成服务", "value": "待完成"},
        ];
      case '10235':
        return [if (!isFood && viewModel.canStartOrder)
          {"name": "开始服务", "value": "待开始"}
        else
          if(viewModel.canFinishOrder)
          {"name": "完成服务", "value": "待完成"},];
      case '10236':
        return [
          if(viewModel.canFinishOrder)
          {"name": "完成服务", "value": "待完成"}
        ];
      default:
        return [];
    }
  }

  Widget btnList(ServiceOrderListData item, String orderId) {
    return Wrap(
      alignment: WrapAlignment.end,
      spacing: 10,
      children: btnStrs(item).map((e) {
        return ElevatedButton(
          onPressed: () {
            Go().push(ServiceOrderDetailPage(
              showDetail: false,
              orderId: orderId,
              handleStatus: e['value'],
            ));
          },
          child: Text(e['name']!),
          style: ButtonStyle(
              shape: WidgetStateProperty.all(StadiumBorder()),
              elevation: WidgetStateProperty.all(0),
              padding:
                  WidgetStateProperty.all(EdgeInsets.symmetric(horizontal: 8)),
              maximumSize: WidgetStateProperty.all(Size.fromHeight(36))),
        );
      }).toList(),
    );
  }

  String statusHandle(String statusId) {
    switch (statusId) {
      case '10233':
        return '接单';

      case '10235':
      case '10236':
        return '完成服务';
      default:
        return '';
    }
  }

  String handleStatus(String statusId) {
    switch (statusId) {
      case '10233':
        return '待接单';

      case '10235':
        return "待开始";
      case '10236':
        return '待完成';
      default:
        return '';
    }
  }

  @override
  EdgeInsets get listPadding => EdgeInsets.symmetric(vertical: 16);

  @override
  Widget get separatorDivider => Container(
        height: 10,
      );

  @override
  bool get canPullUp => true;

  @override
  SimpleServiceOrderListViewModel createViewModel() {
    return SimpleServiceOrderListViewModel(context, '1111');
  }
}
